package com.studyroom.controller;

import com.studyroom.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDateTime;
import com.studyroom.utils.FileUploadUtil;
import com.studyroom.entity.Snack;
import com.studyroom.service.SnackService;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/admin/snacks")
public class AdminSnackController {
    
    private final SnackService snackService;
    
    @Value("${file.upload.path}")
    private String uploadPath;
    
    private static final Logger log = LoggerFactory.getLogger(AdminSnackController.class);
    
    public AdminSnackController(SnackService snackService) {
        this.snackService = snackService;
    }
    
    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 确保目录存在
            String projectPath = System.getProperty("user.dir");
            File dir = new File(projectPath + "/backend/src/main/resources/uploads");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            File dest = new File(dir.getAbsolutePath() + File.separator + filename);
            file.transferTo(dest);
            
            // 返回相对路径
            return Result.success("/uploads/" + filename);
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/create")
    public Result<?> createSnack(@RequestBody Snack snack) {
        // 验证必要字段
        if (snack.getName() == null || snack.getPrice() == null) {
            return Result.error("名称和价格不能为空");
        }
        snack.setCreatedAt(LocalDateTime.now());
        snack.setUpdatedAt(LocalDateTime.now());
        snackService.save(snack);
        return Result.success(null, "添加成功");
    }
} 